/*
 * @Descripttion: find / findIndex 原理探究
 * @version: 
 * @Author: wtzhang
 * @Date: 2021-05-20 14:52:38
 * @LastEditors: wtzhang
 * @LastEditTime: 2021-05-28 08:46:09
 */

let person = [
  {id: 1, name: 'jack'},
  {id: 2, name: 'rose'},
  {id: 3, name: 'jasper'},
  {id: 4, name: 'herman'}
]

// 自封装 find 查找元素
Array.prototype.myFind = function (callback) {
  // callback = function(item, index) { return item.id === 2 }
  for (let i = 0; i < this.length; i++) {
    if (callback(this[i], i)) {
      return this[i]
    }
  }
}
// 自封装 findIndex 查找目标元素下标
Array.prototype.myFindIndex = function (callback) {
  for (let j = 0; j < this.length; j++) {
    if (callback(this[j], j)) {
      return j
    }
  }
}

let res = person.myFind((item, index) => {
  return item.id === 2
})
let resIndex = person.myFindIndex((item, index) => {
  return item.id === 2
})

console.log('目标数据：', res);
console.log('目标数据下标：', resIndex);